<?php
/**
 * 功能描述：此接口用于针对商品一级分类或子商品goods_id查找对应的促销活动
 *
 * 作者：zenan.li
 *
 * Created by Zend Studio.
 * User: zenan.li (FDG348)
 * Date: 2017/11/06
 * Time: 16:31
 */

namespace common\helps;

use common\models\CouponReceive;
use common\models\Coupon;
use Yii;

class getCoupon{
    
    public function getCouponData($goods_id,$category_ids = [],$use_mark=COUPON_USE_MARK_GOODS_DETAIL){
        $result = ['code'=>500,'data'=>'','message'=>''];
        try {
            if (empty($goods_id)) {
                throw new \Exception('子商品id必传');
            }
            if (!is_array($goods_id)){
                throw new \Exception('子商品传参格式有误');
            }
            $today = date('Y-m-d');
            $new_category_ids = [];
            if (count(array_filter($category_ids)) > 0){
                $normal_id = array_keys($GLOBALS['_GOODS_GENRE_TYPE']);
                foreach ($category_ids as $category_id){
                    if (!in_array($category_id, $normal_id)){
                        $new_category_ids[] = -1;
                    }else{
                        $new_category_ids[] = $category_id;
                    }
                }
            }
            $new_category_ids[] = 0;
            $new_category_ids = is_array($new_category_ids) && count($new_category_ids) > 0 ? array_unique($new_category_ids) : [];
            $coupon_arr = [];
            $sql_where = 'j_coupon.use_mark like "%'.$use_mark.'%" and j_coupon.use_flg=1 and "'.$today .'" between j_coupon.coupon_start_time and j_coupon.coupon_end_time';
            $sql_where .= ' and (j_coupon_plus.category_id in ('.implode(',', $new_category_ids).') or j_coupon_plus.goods_id in ("'.implode('","', $goods_id).'"))';
            //$sql_where .= ' or (j_coupon_plus.category_id=0 and j_coupon.use_flg = 1 and "'.$today.'" between j_coupon.coupon_start_time and j_coupon.coupon_end_time)';
            $select = 'j_coupon.id,j_coupon.type,j_coupon.title,j_coupon.highlight,j_coupon.coupon_start_time,j_coupon.coupon_end_time,j_coupon.release_number,j_coupon.draw_count,j_coupon.content,j_coupon_plus.goods_id,j_coupon_plus.category_id';
            $coupon = Coupon::find()->select($select)->joinWith('couponPlus')->where($sql_where);
            $coupon = $coupon->asArray()->all();
            if (is_array($coupon) && count($coupon) > 0)foreach ($coupon as $coupon_val){
                unset($coupon_val['couponPlus']);
                $coupon_val['goods_id'] = $coupon_val['goods_id'] ? $coupon_val['goods_id'] : '';
                $coupon_arr[] = $coupon_val;
            }
            $result['code'] = 200;
            $result['data'] = $coupon_arr;
            $result['message'] = '成功';
        } catch (\Exception $e) {
            $result['message'] = $e->getMessage();
        }
        return json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    public function receiveCoupon($memberInfo,$coupon_ids,$use_mark=COUPON_USE_MARK_GOODS_DETAIL){
        $result = ['code'=>500,'message'=>''];
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!tools::arrayHasValue($memberInfo,'id')){
                throw new \Exception('登录信息不存在,请重新登录',404);
            }
            if (!is_array($coupon_ids) || count($coupon_ids) == 0) {
                throw new \Exception('优惠券传送格式不正确',500);
            }
            $cannot_receive_coupon_id = [];
            $coupon_show = Coupon::find()->where(['id'=>$coupon_ids])->asArray()->all();
            //如果无可领取优惠券，则报错
            $not_show_coupon = [];
            if (is_array($coupon_show) && count($coupon_show) > 0)foreach ($coupon_show as $coupon_val){
                if ($coupon_val['release_number'] <= $coupon_val['draw_count']){
                    $not_show_coupon[] = $coupon_val['id'];
                }
            }
            //获取领取过的优惠券
            $where_coupon = ['and',['in','coupon_id',$coupon_ids],['cust_master_id'=>$memberInfo->id]];
            $coupon_receive = CouponReceive::find()->select('coupon_id')->where($where_coupon)->asArray()->all();
            //优惠券id集合中的个数大于已领取优惠券个数，则直接跳过
            if (count($coupon_receive) < count($coupon_ids)){
                $receive_coupon_id = count($coupon_receive) > 0 ? array_column($coupon_receive, 'coupon_id') : [];
                foreach ($coupon_ids as $coupon_id){
                    if (in_array($coupon_id, $receive_coupon_id)){
                        $cannot_receive_coupon_id[] = $coupon_id;
                    }else{
                        //如果draw_count小于release_number，则draw_count+1
                        $update_coupon = Coupon::updateAllCounters(['draw_count'=>1],'id=:id and draw_count<release_number',[':id'=>$coupon_id]);
                        if (!$update_coupon){
                            $cannot_receive_coupon_id[] = $coupon_id;
                        }
                    }
                }
                $new_coupon_id = array_diff($coupon_ids, $receive_coupon_id);
                $coupon = Coupon::find()->where(['id'=>$new_coupon_id])->asArray()->all();
                if (is_array($coupon) && count($coupon) > 0){
                    //获取优惠券验证码
                    $sms_code = tools::roundCode();
                    $num = 0;
                    foreach ($coupon as $coupon_val){
                        if (in_array($coupon_val['id'], $cannot_receive_coupon_id)){
                            continue;
                        }
                        $draw_count = intval($coupon_val['draw_count']);
                        $source_val = [
                            'coupon_id'=>$coupon_val['id'],
                            'mobile'=>$memberInfo->mobile,
                            'sms_verification'=>intval($sms_code),
                            'type'=>$coupon_val['type'],
                            'title'=>$coupon_val['title'],
                            'highlight'=>$coupon_val['highlight'],
                            'coupon_start_time'=>$coupon_val['coupon_start_time'],
                            'coupon_end_time'=>$coupon_val['coupon_end_time'],
                            'content'=>$coupon_val['content'],
                            'release_number'=>$coupon_val['release_number'],
                            'draw_count'=>intval($coupon_val['draw_count']),
                            'use_mark'=>$use_mark,
                            'cust_master_id'=>$memberInfo->id,
                            'receive_time'=>date('Y-m-d H:i:s'),
                        ];
                        $res = Yii::$app->db->createCommand()->insert('j_coupon_receive',$source_val)->execute();
                        if (!$res){
                            throw new \Exception('优惠券领取失败',500);
                        }
                        $num++;
                        if ($num == 1){
                            $return_data = tools::sendMobileCode($memberInfo->mobile, $sms_code,'sms_coupon_get');
                            if (!$return_data){
                                throw new \Exception('优惠券验证码发送失败',500);
                            }
                        }
                    }
                }
            }
            $transaction->commit();
            $result['code'] = 200;
            $result['data'] = array_unique($not_show_coupon);
            $result['message'] = '成功';
        } catch (\Exception $e) {
            $transaction->rollBack();
            $result['message'] = $e->getMessage();
            $result['code'] = $e->getCode();
        }
        return json_encode($result,JSON_UNESCAPED_UNICODE);
    }
}